using System;
using System.IO;
using System.Text;
using System.Collections.Generic; // Added for List

namespace DidaManager.Native.Network
{
    /// <summary>
    /// INI文件处理工具类
    /// </summary>
    public class IniFileHelper
    {
        private readonly string _filePath;
        private readonly object _lockObject = new object();

        public IniFileHelper(string filePath)
        {
            _filePath = filePath;
        }

        /// <summary>
        /// 读取INI文件中的值
        /// </summary>
        /// <param name="section">节名</param>
        /// <param name="key">键名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>读取到的值，如果不存在则返回默认值</returns>
        public string ReadValue(string section, string key, string defaultValue = "")
        {
            try
            {
                if (!File.Exists(_filePath))
                    return defaultValue;

                lock (_lockObject)
                {
                    var lines = File.ReadAllLines(_filePath, Encoding.UTF8);
                    bool inTargetSection = false;

                    foreach (var line in lines)
                    {
                        var trimmedLine = line.Trim();
                        
                        // 跳过空行和注释行
                        if (string.IsNullOrEmpty(trimmedLine) || trimmedLine.StartsWith(";") || trimmedLine.StartsWith("#"))
                            continue;

                        // 检查是否是节名
                        if (trimmedLine.StartsWith("[") && trimmedLine.EndsWith("]"))
                        {
                            var currentSection = trimmedLine.Substring(1, trimmedLine.Length - 2).Trim();
                            inTargetSection = string.Equals(currentSection, section, StringComparison.OrdinalIgnoreCase);
                            continue;
                        }

                        // 如果在目标节中，查找键值对
                        if (inTargetSection)
                        {
                            var separatorIndex = trimmedLine.IndexOf('=');
                            if (separatorIndex > 0)
                            {
                                var currentKey = trimmedLine.Substring(0, separatorIndex).Trim();
                                if (string.Equals(currentKey, key, StringComparison.OrdinalIgnoreCase))
                                {
                                    var value = trimmedLine.Substring(separatorIndex + 1).Trim();
                                    return value;
                                }
                            }
                        }
                    }
                }

                return defaultValue;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"读取INI文件失败: {ex.Message}");
                return defaultValue;
            }
        }

        /// <summary>
        /// 写入INI文件中的值
        /// </summary>
        /// <param name="section">节名</param>
        /// <param name="key">键名</param>
        /// <param name="value">值</param>
        /// <returns>是否写入成功</returns>
        public bool WriteValue(string section, string key, string value)
        {
            try
            {
                lock (_lockObject)
                {
                    // 确保目录存在
                    var directory = Path.GetDirectoryName(_filePath);
                    if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    var lines = new List<string>();
                    bool sectionExists = false;
                    bool keyExists = false;
                    bool inTargetSection = false;

                    // 读取现有内容
                    if (File.Exists(_filePath))
                    {
                        lines.AddRange(File.ReadAllLines(_filePath, Encoding.UTF8));
                    }

                    // 查找节和键是否存在
                    for (int i = 0; i < lines.Count; i++)
                    {
                        var line = lines[i];
                        var trimmedLine = line.Trim();

                        if (trimmedLine.StartsWith("[") && trimmedLine.EndsWith("]"))
                        {
                            var currentSection = trimmedLine.Substring(1, trimmedLine.Length - 2).Trim();
                            if (string.Equals(currentSection, section, StringComparison.OrdinalIgnoreCase))
                            {
                                sectionExists = true;
                                inTargetSection = true;
                            }
                            else
                            {
                                inTargetSection = false;
                            }
                            continue;
                        }

                        if (inTargetSection && !string.IsNullOrEmpty(trimmedLine) && !trimmedLine.StartsWith(";") && !trimmedLine.StartsWith("#"))
                        {
                            var separatorIndex = trimmedLine.IndexOf('=');
                            if (separatorIndex > 0)
                            {
                                var currentKey = trimmedLine.Substring(0, separatorIndex).Trim();
                                if (string.Equals(currentKey, key, StringComparison.OrdinalIgnoreCase))
                                {
                                    keyExists = true;
                                    lines[i] = $"{key}={value}";
                                    break;
                                }
                            }
                        }
                    }

                    // 如果键不存在但节存在，在节末尾添加键值对
                    if (!keyExists && sectionExists)
                    {
                        for (int i = 0; i < lines.Count; i++)
                        {
                            var line = lines[i];
                            var trimmedLine = line.Trim();

                            if (trimmedLine.StartsWith("[") && trimmedLine.EndsWith("]"))
                            {
                                var currentSection = trimmedLine.Substring(1, trimmedLine.Length - 2).Trim();
                                if (string.Equals(currentSection, section, StringComparison.OrdinalIgnoreCase))
                                {
                                    // 找到节，在下一个节之前插入键值对
                                    int insertIndex = i + 1;
                                    while (insertIndex < lines.Count)
                                    {
                                        var nextLine = lines[insertIndex].Trim();
                                        if (nextLine.StartsWith("[") && nextLine.EndsWith("]"))
                                            break;
                                        insertIndex++;
                                    }
                                    lines.Insert(insertIndex, $"{key}={value}");
                                    break;
                                }
                            }
                        }
                    }
                    // 如果节不存在，在文件末尾添加节和键值对
                    else if (!sectionExists)
                    {
                        if (lines.Count > 0 && !string.IsNullOrEmpty(lines[lines.Count - 1].Trim()))
                        {
                            lines.Add(""); // 添加空行分隔
                        }
                        lines.Add($"[{section}]");
                        lines.Add($"{key}={value}");
                    }

                    // 写入文件
                    File.WriteAllLines(_filePath, lines, Encoding.UTF8);
                    return true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"写入INI文件失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 检查文件是否存在
        /// </summary>
        /// <returns>文件是否存在</returns>
        public bool Exists()
        {
            return File.Exists(_filePath);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <returns>是否删除成功</returns>
        public bool Delete()
        {
            try
            {
                if (File.Exists(_filePath))
                {
                    File.Delete(_filePath);
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除INI文件失败: {ex.Message}");
                return false;
            }
        }
    }
} 